import 'dart:convert';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/dialog/info_dialog.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/location/locationUtil.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/regexp_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/report_widget/loading_utils.dart';
import 'package:wallet_utils/toast.dart';
import '../api/home_api.dart';
import '../bean/basicInfoBean.dart';
import '../bean/controlBean.dart';
import '../bean/controlEntryBean.dart';
import '../bean/iconDetailBean.dart';
import '../bean/userInfoBean.dart';
import 'state.dart';

class ContactPersonLogic extends GetxController {
  final ContactPersonState state = ContactPersonState();
  num? face;
  num? isShowIdCard;
  num? channelAuthType;
  BasicInfoBean? basicBean;
  DataInfo? userInfo;
  String? urgentContactName = '';
  String? commonContactName = '';
  ControlEntry? dataInfo;
  bool isShowIncoming=false;
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      isShowIncoming = Get.arguments['isShowIncoming'];
      face = Get.arguments['face'];
      isShowIdCard = Get.arguments['isShowIdCard'];
      channelAuthType = Get.arguments['channelAuthType'];
    }
    rootBundle.loadString('assets/authInfo.json').then((address) {
      var data = json.decode(address);
      basicBean = BasicInfoBean.fromJson(data);
    });
    upPro();
    channelIncomingControl();
    getAppUserInfoAll();
  }

  void upPro() {
    state.proState = true;
    if (isShowIdCard == 0) {
      state.proText = '50%';
      state.percent = 140;
    } else {
      if (face == 1) {
        state.proText = '60%';
        state.percent = 168;
      } else if (face == 0) {
        state.proText = '90%';
        state.percent = 252;
      }
    }
    update();
  }

  //件信息详情信息接口（后置）
  void incomingDetailV2() async {
    HomeApi.incomingDetailV2(
        state.detailBean,
        BaseCallback(onSuccess: (map) async {
          Get.back();
          face = map['data']['isShowFace'];
          if (face == 1) {
            WidgetsFlutterBinding.ensureInitialized();
            state.cameras = await availableCameras();
            /// 获取设备摄像头，默认0:后置 1:前置
            state.firstCamera = state.cameras!.first;
            Get.toNamed(BaseRouterConfig.faceRecognition, arguments: {
              'isShowIncoming': isShowIncoming,
              'camera': state.cameras,
            });
          } else {
            if(isShowIncoming){
              Get.toNamed(BaseRouterConfig.result);
            }else{
              Get.toNamed(BaseRouterConfig.auditRejection);
            }
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            Get.back();
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  //件信息详情信息接口（前置）
  void incomingDetail() async {
    HomeApi.incomingDetail(
        state.detailBean,
        BaseCallback(onSuccess: (map) async {
          Get.back();
          face = map['data']['isShowFace'];
          if (face == 1) {
            WidgetsFlutterBinding.ensureInitialized();
            state.cameras = await availableCameras();
            /// 获取设备摄像头，默认0:后置 1:前置
            state.firstCamera = state.cameras!.first;
            Get.toNamed(BaseRouterConfig.faceRecognition, arguments: {
              'isShowIncoming': isShowIncoming,
              'camera': state.cameras,
            });
          } else {
            if(isShowIncoming){
              Get.toNamed(BaseRouterConfig.result);
            }else{
              Get.toNamed(BaseRouterConfig.auditRejection);
            }

          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            Get.back();
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  void submit() {
    if (state.controlList.isEmpty) {
      ToastUtils.showToast('请填写基本信息');
    } else {
      state.urgentLiaison?.clear();
      state.commonLiaison?.clear();
      state.detailBean?.step = 2;
      for (int i = 0; i < state.controlList.length; i++) {
        if (state.controlList[i].title == '职业身份(单选)') {
          state.detailBean?.dwellAddress = state.controlList[i].contentController?.text;
          state.detailBean?.job = state.controlList[i].unitController?.text;
        }
        if (state.controlList[i].title == '公司类型(单选)') {
          state.detailBean?.comAddress = state.controlList[i].contentController?.text;
          state.detailBean?.comTel = state.controlList[i].unitController?.text;
        }
        if (state.controlList[i].title == '紧急联系人') {
          state.urgentLiaison!.add(UrgentLiaison(
              state.controlList[i].contentController?.text,  state.controlList[i].unitController?.text, urgentContactName, 1));
        }
        if (state.controlList[i].title == '常用联系人') {
          state.commonLiaison!.add(CommonLiaison(
              state.controlList[i].contentController?.text,    state.controlList[i].unitController?.text,commonContactName, 0));
        }
      }
      if (state.detailBean!.profession!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('请选择职业身份');
      } else if (state.detailBean!.dwellAddress!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('居住地址不能为空');
      } else if (state.detailBean!.job!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('工作单位不能为空');
      } else if (state.detailBean!.comType!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('请选择公司类型');
      }  else if (state.detailBean!.comAddress!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('公司地址不能为空');
      } else if (state.detailBean!.comTel!.isEmpty && dataInfo?.isShowProfession == 1) {
        ToastUtils.showToast('公司电话不能为空');
      }

      else if (dataInfo?.isShowUrgentLiaison == 1) {
        if (urgentContactName!.isEmpty) {
          ToastUtils.showToast('请选择紧急联系人关系');
          return;
        } else if (state.urgentLiaison![0].name!.isEmpty) {
          ToastUtils.showToast('紧急联系人姓名不能为空');
          return;
        } else if (state.urgentLiaison![0].contact!.isEmpty) {
          ToastUtils.showToast('请选择紧急联系人关系');
          return;
        }
        if(!RegExpUtils.regExpMatchPhone(state.urgentLiaison![0].mobile!)){
          ToastUtils.showToast('请输入正确的紧急联系人手机号');
          return;
        }
      }
      if (dataInfo?.isShowCommonLiaison == 1) {
        if (commonContactName!.isEmpty) {
          ToastUtils.showToast('请选择常用联系人关系');
          return;
        } else if (state.commonLiaison![0].name!.isEmpty) {
          ToastUtils.showToast('常用联系人姓名不能为空');
          return;
        } else if (state.commonLiaison![0].contact!.isEmpty) {
          ToastUtils.showToast('请选择常用联系人关系');
          return;
        }
        if(!RegExpUtils.regExpMatchPhone(state.commonLiaison![0].mobile!)){
          ToastUtils.showToast('请输入正确的常用联系人手机号');
          return;
        }
      }
      state.detailBean?.commonLiaison = state.commonLiaison;
      state.detailBean?.urgentLiaison = state.urgentLiaison;
      LoadingUtils.showLoading(Get.context!, isCanBack: false);
      if (isShowIdCard == 0) {
        incomingDetail();
      } else {
        if (channelAuthType == 1) {
          incomingDetail();
        } else {
          incomingDetailV2();
        }
      }
    }
  }

  void infoDialog() {
    showDialog(
        context: Get.context!,
        builder: (context) {
          return InfoDialog("放弃填写，将无法评估您的额度", title: '温馨提示', yesStr: '继续填写资料', yesCallback: () {
            Get.back();
          });
        });
  }

  //进件控制页
  void channelIncomingControl() async {
    HomeApi.channelIncomingControl(BaseCallback(onSuccess: (map) {
      ControlEntryBean controlEntryBean = ControlEntryBean.fromJson(map);
      if (controlEntryBean.data != null) {
        dataInfo = controlEntryBean.data;
        if (dataInfo?.isShowProfession == 1) {
          IsShowProfession? profession = basicBean?.data?.isShowProfession;
          profession?.proContent?.forEach((element) {
            state.profession.add(ChildData(
              element.text,
              false,
            ));
          });
          state.controlList.add(
            ControlBean(
              profession?.title,
              state.profession,
              0,
              editType: 2,
              leftContent: '居住地址',
              leftUnit: '工作单位',
              contentController: TextEditingController(),
              unitController: TextEditingController(),
            ),
          );

        }
//公司类型
        if (dataInfo?.isShowProfession == 1) {
          IsShowCom? company = basicBean?.data?.isShowCom;
          company?.comContent?.forEach((element) {
            state.comContent.add(ChildData(
              element.text,
              false,
            ));
          });
          state.controlList.add(
            ControlBean(
              company?.title,
              state.comContent,
              0,
              editType: 4,
              leftContent: '公司地址',
              leftUnit: '公司电话',
              contentController: TextEditingController(),
              unitController: TextEditingController(),
            ),
          );

        }
        if (dataInfo?.isShowUrgentLiaison == 1) {
          IsShowUrgentLiaison? urgentLiaison = basicBean?.data?.isShowUrgentLiaison;
          urgentLiaison?.urgentContent?.forEach((element) {
            state.urgentContent.add(ChildData(
              element.text,
              false,
            ));
          });
          state.controlList.add(ControlBean(
            urgentLiaison?.title,
            state.urgentContent,
            0,
            editType: 3,
            leftContent: '姓名',
            leftUnit: '手机号',
            contentController: TextEditingController(),
            unitController: TextEditingController(),
          ));
        }
        if (dataInfo?.isShowCommonLiaison == 1) {
          IsShowCommonLiaison? commonLiaison = basicBean?.data?.isShowCommonLiaison;
          commonLiaison?.liaisonContent?.forEach((element) {
            state.liaisonContent.add(ChildData(
              element.text,
              false,
            ));
          });
          state.controlList.add(ControlBean(
            commonLiaison?.title,
            state.liaisonContent,
            0,
            editType: 3,
            leftContent: '姓名',
            leftUnit: '手机号',
            contentController: TextEditingController(),
            unitController: TextEditingController(),
          ));
        }
        LogUtils.d('集合内容 ${state.controlList.toString()}');
        update();
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  //查询用户及进件所有信息
  void getAppUserInfoAll() async {
    HomeApi.getAppUserInfoAll(BaseCallback(onSuccess: (map) {
      UserInfoBean userInfoBean = UserInfoBean.fromJson(map);
      if (userInfoBean.data != null) {
        userInfo = userInfoBean.data;
        //职业身份
        if (userInfo?.userDetail?.profession != null) {
          state.profession.forEach((element) {
            if (userInfo?.userDetail?.profession == element.name) {
              element.isSelect = true;
              state.detailBean?.profession = element.name;
            }
          });
        }

        update();
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  void isCheckStatus(position, index) {
    for (int i = 0; i < state.controlList.length; i++) {
      if (index == i) {
        if (state.controlList[i].type == 0) {
          for (int j = 0; j < state.controlList[i].childData!.length; j++) {
            if (position == j) {
              state.controlList[i].childData![j].isSelect = true;
              var name = state.controlList[i].childData![j].name;

              if (state.controlList[i].title == '职业身份(单选)') {
                state.detailBean?.profession = name;
              }
              if (state.controlList[i].title == '紧急联系人') {
                urgentContactName = name;
              }
              if (state.controlList[i].title == '常用联系人') {
                commonContactName = name;
              }
              if (state.controlList[i].title == '公司类型(单选)') {
                if(name == "外商投资企业"){
                  state.detailBean?.comType = "1";
                }else if(name == "个体工商户"){
                  state.detailBean?.comType = "2";
                }else if(name == "政府机关"){
                  state.detailBean?.comType = "3";
                }else if(name == "私营"){
                  state.detailBean?.comType = "4";
                }else if(name == "国企"){
                  state.detailBean?.comType = "5";
                }else if(name == "合资"){
                  state.detailBean?.comType = "6";
                }else if(name == "民营"){
                  state.detailBean?.comType = "7";
                }else if(name == "事业单位"){
                  state.detailBean?.comType = "8";
                }else if(name == "有限责任公司"){
                  state.detailBean?.comType = "9";
                }else if(name == "股份责任公司"){
                  state.detailBean?.comType = "10";
                }else if(name == "独资企业"){
                  state.detailBean?.comType = "11";
                }else if(name == "合伙制企业"){
                  state.detailBean?.comType = "12";
                }else{
                  state.detailBean?.comType = "13";
                }
              }
            } else {
              state.controlList[i].childData![j].isSelect = false;
            }
          }
        } else {
          for (int j = 0; j < state.controlList[i].childData!.length; j++) {
            if (position == j) {
              var name = state.controlList[i].childData![j].name;
              state.controlList[i].childData![j].isSelect = true;
              if (state.controlList[i].title == '资产信息(多选)') {
                state.detailBean?.propertyItems += name! + ',';
                if ((state.detailBean?.propertyItems)!.endsWith(',')) {
                  state.detailBean?.propertyItems =
                      (state.detailBean?.propertyItems)!.substring(0, (state.detailBean?.propertyItems)!.length - 1);
                }
              }
            }
          }
        }
      }
    }
    update();
  }
 getPlaceholder(String title){
    if(title == '公司类型(单选)'){
      return '请输入公司电话';
    }else if(title == '紧急联系人'){
      return '请输入紧急联系人手机号';
    }else if(title == '常用联系人'){
      return '请输入常用联系人手机号';
    }else if(title == '职业身份(单选)'){
      return '请输入工作单位';
    }
    return '';
 }
  void backPage() {
    EventBusUtils.getInstance().fire(MsgEventBusUtils(MsgEventBusUtils.upHomeStatus, value: false));
    Get.until((route) => (route.settings.name == BaseRouterConfig.main));
  }
}
